package com.relanet.action;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;

import com.relanet.model.NlpUser;
import com.relanet.service.IUserService;
import com.relanet.service.impl.UserServiceImpl;

import weibo4j.User;
import weibo4j.Weibo;
import weibo4j.WeiboException;
import weibo4j.http.AccessToken;
import weibo4j.http.RequestToken;

public class LoginAction extends BaseAction {
	String message;
	RequestToken requestToken = null;
	AccessToken accessToken = null;
	String oauth_verifier;

	/**
	 * 自助注册用户登录方法
	 * 
	 * @return
	 */
	public String login() {

		return SUCCESS;
	}

	/**
	 * 微博登录
	 * 
	 */
	public void loginThroughWeibo() {
		getRequestToken();
	}

	/**
	 * 微博登陆时调用,设置consumerKey,设置call back URL,然后redirect到apt.sina去验证 call back
	 * URL 指向auth.action
	 */
	public void getRequestToken() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpServletResponse response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		System.setProperty("weibo4j.oauth.consumerKey", Weibo.CONSUMER_KEY);
		System.setProperty("weibo4j.oauth.consumerSecret",
				Weibo.CONSUMER_SECRET);

		Weibo weibo = new Weibo();
		try {
			requestToken = weibo
					.getOAuthRequestToken("http://localhost:8080/page/auth.action");
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		session.setAttribute("requestToken", requestToken);
		try {
			response
					.sendRedirect("http://api.t.sina.com.cn/oauth/authorize?oauth_token="
							+ requestToken.getToken());
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	/**
	 * call back URL: auth.action调用该方法,获取授权信息
	 * 
	 * @return 正常返回跳转到登陆成功后页面
	 */
	public String getAccessToken() {
		HttpServletRequest request = ServletActionContext.getRequest();
		HttpSession session = request.getSession();
		requestToken = (RequestToken) session.getAttribute("requestToken");
		// oauth_verifier = request.getParameter("oauth_verifier"); //这个地方不能这么调用
		// 此时struts的请求过来后会给这个oauth_verifier自动赋值 你们可以打个日志出来看下。

		Weibo weibo = new Weibo();
		try {
			accessToken = weibo.getOAuthAccessToken(requestToken.getToken(),
					requestToken.getTokenSecret(), oauth_verifier);
		} catch (WeiboException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		session.setAttribute("accessToken", accessToken);

		// 验证通过

		System.out.println("accessToken token:[" + accessToken.getToken()
				+ "] accessToken token Secret :["
				+ accessToken.getTokenSecret() + "]");
		weibo.setOAuthAccessToken(accessToken);

		// 验证是否首次登陆
		IUserService userService = new UserServiceImpl();
		User user = null;
		try {
			user = weibo.verifyCredentials();
		} catch (WeiboException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		NlpUser nUser = null;
		nUser = userService.isFirstLonin(user.getId(), 2);
		if (nUser == null) {
			// 首次登陆记录用户

			nUser = new NlpUser();
			nUser.setNickname(user.getScreenName());// 昵称
			nUser.setIsregister(1);// 标识是否为注册用户 0-注册用户 1-新浪用户 2-未登录系统用户
			nUser.setSina_uid(user.getId());// 新浪用户ID
			nUser.setAccess_token(accessToken.getToken());// 授权后得到访问API的token
			nUser.setToken_secret(accessToken.getTokenSecret());// API服务器生成的加密串
			nUser.setFollowers_count(user.getFollowersCount());// 用户的粉丝数，每次登录时更新
			nUser.setDomain_name(user.getUserDomain());// 用户设置的个性化域名
			if (!userService.recordUser(nUser)) {
				message = "record user error";
			}

		} else {
			// 非首次登陆,更新用户信息
			nUser.setFollowers_count(user.getFollowersCount());// 用户的粉丝数，每次登录时更新
			if (!userService.updateUser(nUser)) {
				message = "update user error";
			}
		}

		System.out.println(user.getId());
		System.out.println(user);
		session.setAttribute("user", user);

		message = "login through weibo success!";
		return SUCCESS;
	}

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

	public String getOauth_verifier() {
		return oauth_verifier;
	}

	public void setOauth_verifier(String oauthVerifier) {
		oauth_verifier = oauthVerifier;
	}

	public void setRequestToken(RequestToken requestToken) {
		this.requestToken = requestToken;
	}

	public void setAccessToken(AccessToken accessToken) {
		this.accessToken = accessToken;
	}

}
